import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home'
import { loginStatus } from '_utils/token.js'

Vue.use(VueRouter)

const routes = [{
  path: '/',
  redirect: '/home'
},
{
  path: '/home',
  name: 'home',
  // 首页
  component: Home,
  meta: {
    needLogin: false,
    keepAlive: true
  }
},
{
  path: '/cate',
  name: 'cate',
  // 分类
  component: () => import('_views/Cate'),
  meta: {
    needLogin: false
  }
},
{
  path: '/cart',
  name: 'cart',
  // 购物车
  component: () => import('_views/Cart'),
  meta: {
    needLogin: true
  }
},
{
  path: '/user',
  name: 'user',
  // 我的
  component: () => import('_views/User'),
  meta: {
    needLogin: true
  }
},
{
  path: '/details/:id',
  name: 'details',
  // 详情
  component: () => import('_views/Details'),
  meta: {
    needLogin: false
  }
},
{
  path: '/itemlist',
  name: 'itemlist',
  // 分类商品列表
  component: () => import('_views/ItemList'),
  meta: {
    needLogin: false
  }
},
{
  path: '/search',
  name: 'search',
  // 搜索
  component: () => import('_views/Search'),
  meta: {
    needLogin: false
  }
},
{
  path: '/searchresult',
  name: 'searchresult',
  // 搜索结果
  component: () => import('_views/SearchResult'),
  meta: {
    needLogin: false
  }
},
{
  path: '/register',
  name: 'register',
  // 注册
  component: () => import('_views/Register'),
  meta: {
    needLogin: false
  }
},
{
  path: '/login',
  name: 'login',
  // 登录
  component: () => import('_views/Login'),
  meta: {
    needLogin: false
  }
},
{
  path: '/order',
  name: 'order',
  // 订单
  component: () => import('_views/Order'),
  meta: {
    needLogin: false
  }
},
{
  path: '/contactsList',
  name: 'contactsList',
  // 联系人列表
  component: () => import('_views/ContactsList'),
  meta: {
    needLogin: true
  }
},
{
  path: '/contactsAdd',
  name: 'contactsAdd',
  // 新增联系人
  component: () => import('_views/ContactsAdd'),
  meta: {
    needLogin: true
  }
},
{
  path: '/contactsUpdate',
  name: 'contactsUpdate',
  // 修改联系人
  component: () => import('_views/ContactsUpdate'),
  meta: {
    needLogin: true
  }
},
{
  path: '/settinguser',
  name: 'settinguser',
  // 修改联系人
  component: () => import('_views/Settinguser'),
  meta: {
    needLogin: true
  }
},
{
  path: '/favor',
  name: 'favor',
  // 修改联系人
  component: () => import('_views/Favor'),
  meta: {
    needLogin: true
  }
}
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  // 判断是否需要做登录鉴权
  if (to.meta.needLogin) {
    // 需要登录鉴权 判断是否登录了
    if (loginStatus()) {
      // 登陆了，直接放行
      next()
    } else {
      // 没有登录 跳转登录页 记录跳转前的登录ip
      next({
        path: '/login',
        query: {
          from: to.path
        }
      })
    }
  } else {
    // 不需要做登录鉴权，直接放行
    next()
  }
})

export default router
